<?php


class PagesController extends AppController {
   
    var $name = 'Pages';
    
    
    var $components = array('RequestHandler','Security');        
    
    function beforeFilter(){
        parent::beforeFilter();
        
            
        
        // ensure our ajax methods are posted
        $this->Security->requirePost('getnodes', 'reorder', 'reparent');
    }
    
    // Pages management 
    
    function admin_index() {
        
        
        $cats = $this->paginate('Page');
        
        $pages=array();
        
        foreach($cats as $c){
            $t=$c;
            $t['Page']['parent']=$this->Page->find('first',array('fields'=>array('name'),'recursive'=>-1,'conditions'=>array('id'=>$c['Page']['parent_id'])));
            $pages[]=$t;
        }

        $this->set(compact('pages'));

    }
    
    
    
    // add Pages
    
    function admin_add($id=0) {
            
        if(!empty($this->data)):
        
            
            
            if(!$id)
                $this->data['Page']['created'] = date('Y-m-d H:i:s');
            $this->data['Page']['modified'] = date('Y-m-d H:i:s');
            
            $this->data['Page']['name']=strtolower(str_replace(' ','_',$this->data['Page']['name']));
            
            if(!$this->data["Page"]["parent_id"])$this->data["Page"]["parent_id"]=null;
            
            if($this->Page->save($this->data)) :
                $this->Session->write('Success',true);
                $this->Session->setFlash('Page Saved!');
                $this->redirect(array('controller' => 'pages', 'action' => 'index'));
                exit;
            endif;
        elseif($id):
        
            $this->Page->id=$id;
            $this->data=$this->Page->read();
            $this->set('id',$id);
        
        endif;
        
        
         $options = array(
            'conditions' => array('NOT' => array('id' => array(0,$id))),
            'recursive' => 0,
            'fields' => array('id','name'),
            'order' => array('lft' => 'ASC'),
        );
        
        $parents = $this->Page->find('list', $options);
        
        $parents=array(0=>' -- (Root Page) --')+$parents;
        
        $this->set(compact('parents'));
        
        
    }
    
    
    // edit Pages
    
    function admin_edit($id=null) {
        
        if($id==null){
            $this->redirect($this->referer());
            exit;
        }
        
        $this->admin_add($id);
                
        $this->render('admin_add');
        
    }
    
    
    
    // delete Page
    function admin_delete($id=null) {
    
    
        if($id==null){
            $this->redirect($this->referer());
            exit;
        }

        if($this->Page->delete(array('Page.id'=>$id))) :
            
            $this->Session->write('Success',true);
            $this->Session->setFlash('Page deleted sucessfully');
            
        endif;
        
        
        $this->redirect($this->referer());
        exit;
    }
   

    
    
     function display() {
        $path = func_get_args();

        $count = count($path);
        if (!$count) {
            $this->redirect('/');
        }
        $page =  null;

        if (!empty($path[0])) {
            $page = $path[0];
        }
        
        $details=$this->Page->find(array('name'=>$page));
        if(!$details)
            $this->render('not-found');
        
        $content=$details['Page'];
        
        
        $this->set(compact('content'));
        
    }
    
    
    
   
   function admin_tree(){
        
    }
    
    
    
    
    
    
    function admin_getnodes() {
        
        
        $this->layout='admin/ajax_category';
        
        // retrieve the node id that Ext JS posts via ajax
        $parent = intval($this->params['form']['node']);
        
        // find all the nodes underneath the parent node defined above
        // the second parameter (true) means we only want direct children
        $nodes = $this->Page->children($parent, true);
        
        // send the nodes to our view
        $this->set(compact('nodes'));
        
    }
    
    function admin_reorder() {
        
        // retrieve the node instructions from javascript
        // delta is the difference in position (1 = next node, -1 = previous node)
        
        $node = intval($this->params['form']['node']);
        $delta = intval($this->params['form']['delta']);
        
        if ($delta > 0) {
            $this->Page->movedown($node, abs($delta));
        } elseif ($delta < 0) {
            $this->Page->moveup($node, abs($delta));
        }
        
        
        
        // send success response
        exit('1');
        
    }
    
    function admin_reparent(){
        
        $node = intval($this->params['form']['node']);
        $parent = intval($this->params['form']['parent']);
        $position = intval($this->params['form']['position']);
        
        // save the employee node with the new parent id
        // this will move the employee node to the bottom of the parent list
        
        $this->Page->id = $node;
        $this->Page->saveField('parent_id', $parent);
        
        // If position == 0, then we move it straight to the top
        // otherwise we calculate the distance to move ($delta).
        // We have to check if $delta > 0 before moving due to a bug
        // in the tree behaviour (https://trac.cakephp.org/ticket/4037)
        
        if ($position == 0) {
            $this->Page->moveup($node, true);
        } else {
            $count = $this->Page->childcount($parent, true);
            $delta = $count-$position-1;
            if ($delta > 0) {
                $this->Page->moveup($node, $delta);
            }
        }
        
        Cache::delete('front_menu', 'news');
        // send success response
        exit('1');
        
    } 
    
    
    function admin_rebuild_tree($parent, $left) {
       
        
        $right = $left + 1;   

        $options = array(
            'conditions' => array(
                'parent_id' => $parent,
            ),
            'fields' => array('id'),
            'order' => array('id' => 'ASC'),
            );
        
        $this->Page->recursive = -1;
        $children = $this->Page->find('all', $options);
        if($children) :
            foreach($children as $item) :
                $right = $this->admin_rebuild_tree($item['Page']['id'], $right);
            endforeach;
        endif;
        
        $this->Page->updateAll(
            array(
                'lft' => $left,
                'rght' => $right,
            ),
            array(
                'id' => $parent,
            )
        );
        
        Cache::delete('front_menu', 'news');
                   
        return $right + 1;
    }
    
}
?>
